package com.newmuis.open.codeeval.easy;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 * CodeEval.com > Easy Challenges > Sum of Digits
 * 
 * Description:
 * 
 * Given a positive integer, find the sum of its constituent digits.
 * 
 * Input sample:
 * 
 * The first argument will be a text file containing positive integers, one per line. e.g.
 * 
 * 23
 * 496
 * 
 * Output sample:
 * 
 * Print to stdout, the sum of the numbers that make up the integer, one per line.
 * e.g.
 * 
 * 5
 * 19
 * 
 * @author Jonathan Newmuis (jon@newmuis.com)
 * @category easy
 * 
 */
public class sum_digits {
	/**
	 * @param args should contain only one CLI argument: the path to an input file which specifies
	 *            the input in the defined format.
	 * @throws IOException if there is a problem reading the given input file.
	 */
	public static void main(final String[] args) throws IOException {
		// Verify input argument length.
		if (args.length < 1) {
			throw new RuntimeException("Must specify input file path.");
		} else if (args.length > 1) {
			throw new RuntimeException("Illegal input arguments specified.");
		}

		// Read file from specified path.
		final BufferedReader reader = new BufferedReader(new FileReader(new File(args[0])));
		String line;

		while ((line = reader.readLine()) != null) {
			int sum = 0;

			// Iterate through the digits.
			final int digitCount = line.length();
			for (int i = 0; i < digitCount; i++) {
				try {
					// Use this instead of Character.getNumericValue to avoid accidentally parsing
					// non-numeric characters if given invalid input.
					sum += Integer.parseInt(new String(new char[] { line.charAt(i) }));
				} catch (final NumberFormatException e) {
					throw new RuntimeException("Input file contained non-numeric arguments.");
				}
			}

			// Output the sum.
			System.out.println(sum);
		}
	}
}
